package xyz.lwm.lazycat.transaction.execute;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Data
@Slf4j
class TransactionImpl implements Transaction {

    static final Transaction UNOPENABLE = new TransactionImpl(Isolation.DEFAULT, false, false);

    private final Isolation isolation;

    private final boolean open;

    private final boolean readOnly;

    private boolean completed;

    private Transaction parent;

    private final List<Transaction> children = new ArrayList<>();

    private Connection connection;

    @Override
    public void commit() {
        try {
            checkConnection();
            setCompleted(true);
            connection.commit();
        } catch (SQLException e) {
            log.error("commit error", e);
        }
    }

    @Override
    public void rollback() {
        try {
            checkConnection();
            setCompleted(true);
            connection.rollback();
        } catch (SQLException e) {
            log.error("rollback error", e);
        }
    }

    private void checkConnection() {
        if (connection == null) {
            throw new TransactionException("Connection is null because transaction datasource is missing");
        }
    }

    @Override
    public List<Transaction> children() {
        return children;
    }

    @Override
    public void setParent(Transaction parent) {
        this.parent = parent;
        if (parent != null) {
            parent.children().add(this);
        }
    }

}
